/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.devmng.web;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.devmng.entity.*;
import com.thinkgem.jeesite.modules.devmng.service.*;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.service.OfficeService;
import org.apache.ibatis.jdbc.Null;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 设备Controller
 *
 * @author panda
 * @version 2017-12-02
 */
@Controller
@RequestMapping(value = "${adminPath}/devmng/deviceMain")
public class DeviceMainController extends BaseController {

    @Autowired
    private DeviceMainService deviceMainService;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private TaskDetailService taskDetailService;

    @Autowired
    private DevchkItemService devchkItemService;

    @Autowired
    private DevchkItemAnswerService devchkItemAnswerService;

    @Autowired
    private DeviceManualService deviceManualService;

    @ModelAttribute
    public DeviceMain get(@RequestParam(required = false) String id) {
        DeviceMain entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = deviceMainService.get(id);
        }
        if (entity == null) {
            entity = new DeviceMain();
        }

        return entity;
    }

    @RequiresPermissions("devmng:deviceMain:view")
    @RequestMapping(value = {"list", ""})
    public String list(DeviceMain deviceMain, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<DeviceMain> page = deviceMainService.findPage(new Page<DeviceMain>(request, response), deviceMain);
        model.addAttribute("page", page);
        return "modules/devmng/deviceMainList";
    }

    @RequiresPermissions("devmng:deviceMain:view")
    @RequestMapping(value = {"examine"})
    public String examine(DeviceMain deviceMain, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<DeviceMain> page = deviceMainService.findPage(new Page<DeviceMain>(request, response), deviceMain);
        model.addAttribute("page", page);
        return "modules/devmng/deviceMainExamine";

    }

    @RequiresPermissions("devmng:deviceMain:view")
    @RequestMapping(value = {"flag"})
    public String flag(DeviceMain deviceMain,Model model, HttpServletRequest request, HttpServletResponse response) {
        if ("N".equals(deviceMain.getExamine())) {
            deviceMain.setExamine("Y");
        } else if ("Y".equals(deviceMain.getExamine())){
            deviceMain.setExamine("N");
        }
        deviceMainService.save(deviceMain);
        deviceMain.setDeviceName(null);
        deviceMain.setSysOffice(null);
        deviceMain.setDeviceType(null);
        deviceMain.setDeviceCode(null);
        deviceMain.setExamine(null);
        Page<DeviceMain> page = deviceMainService.findPage(new Page<DeviceMain>(request, response), deviceMain);
        model.addAttribute("page", page);

        return "modules/devmng/deviceMainExamine";
    }

    @RequiresPermissions("devmng:deviceMain:view")
    @RequestMapping(value = "form")
    public String form(DeviceMain deviceMain, Model model) {
        List<DeviceManual> manualList = deviceManualService.findListByDeviceMainId(deviceMain.getId());
        if (manualList != null) {
            manualList = deviceManualService.findListByDeviceMainId(deviceMain.getId());
            model.addAttribute("deviceManual",manualList);
        }
        model.addAttribute("deviceMain", deviceMain);
        model.addAttribute("copyFlag", "N");
        model.addAttribute("copyId", deviceMain.getId());
        return "modules/devmng/deviceMainForm";
    }
    @RequiresPermissions("devmng:deviceMain:view")
    @RequestMapping(value = "copy")
    public String copy(DeviceMain deviceMain, Model model) {
        model.addAttribute("deviceMain", deviceMain);
        model.addAttribute("copyFlag", "Y");
        model.addAttribute("copyId", deviceMain.getId());
        deviceMain.setId(null);
        return "modules/devmng/deviceMainForm";
    }
    @RequiresPermissions("devmng:deviceMain:view")
    @RequestMapping(value = "manualDelete")
    public String manualDelete(DeviceManual deviceManual,Model model) {
        deviceManualService.delete(deviceManual);
        deviceManual = deviceManualService.get(deviceManual.getId());
        DeviceMain deviceMain  = deviceMainService.get(deviceManual.getDeviceMain());
        List<DeviceManual> manualList = deviceManualService.findListByDeviceMainId(deviceMain.getId());
        if (manualList != null) {
            manualList = deviceManualService.findListByDeviceMainId(deviceMain.getId());
            model.addAttribute("deviceManual",manualList);
            model.addAttribute("deviceMain", deviceMain);
        }
        return "modules/devmng/deviceMainForm";
    }
    @RequiresPermissions("devmng:deviceMain:edit")
    @RequestMapping(value = "save")
    public String save(DeviceMain deviceMain, MultipartFile deviceImgFile, @RequestParam("deviceManualFile") MultipartFile[] deviceManualFile,
                       Model model, RedirectAttributes redirectAttributes, String copyFlag, String copyId) {
        if (!beanValidator(model, deviceMain)) {
            return form(deviceMain, model);
        }
        if ("Y".equals(copyFlag)) {
            DeviceMain deviceNameUrl = deviceMainService.get(copyId);
            deviceMain.setDeviceManualUrl(deviceNameUrl.getDeviceManualUrl());
            deviceMain.setDeviceManualName(deviceNameUrl.getDeviceManualName());
            deviceMainService.superSave(deviceMain);
            // 如果是复制行为，还需要复制检修项
            DevchkItem devchkItemQuery = new DevchkItem();
            DeviceMain deviceMainQuery = new DeviceMain();
            //设置旧值ID 修改检修项设备ID
            deviceMainQuery.setId(copyId);
            devchkItemQuery.setDeviceMain(deviceMainQuery);
            //遍历出检修项
            List<DevchkItem> devchkItemList = devchkItemService.findList(devchkItemQuery);
                Map<String, String> devchkItemOldId2NewIdMap = new HashMap<String, String>();
                List<DevchkItem> devchkItemSort = new ArrayList<DevchkItem>();
                int num = 0;
                devchkItemSort.add(null);
                for (int i = devchkItemList.size()-1; i >= 0; i--){

                    for (int j = i; j <devchkItemList.size() - 1; j++) {
                        if (devchkItemList.get(j).getSortNum() < devchkItemList.get(j+1).getSortNum() ) {
                            devchkItemSort.set(0,devchkItemList.get(j));
                            devchkItemList.set(j,devchkItemList.get(j+1));
                            devchkItemList.set(j+1,devchkItemSort.get(0));

                        }
                    }

            }
            for (DevchkItem devchkItem: devchkItemList) {
                //获取原先id
                String oldId = devchkItem.getId();
                devchkItem.setId(null);
                DeviceMain deviceMainAdd = new DeviceMain();
                //修改为保存后的id(新)
                deviceMainAdd.setId(deviceMain.getId());
                devchkItem.setDeviceMain(deviceMainAdd);
                devchkItemService.superSave(devchkItem);
                devchkItemOldId2NewIdMap.put(oldId, devchkItem.getId());
            }
            for (Map.Entry<String, String> entry : devchkItemOldId2NewIdMap.entrySet()) {
                List<DevchkItemAnswer> devchkItemAnswerList = devchkItemAnswerService.listByDevchkItemId(entry.getKey());
                for (DevchkItemAnswer devchkItemAnswer : devchkItemAnswerList) {
                    devchkItemAnswer.setId(null);
                    devchkItemAnswer.setDevchkItemId(entry.getValue());
                    devchkItemAnswerService.save(devchkItemAnswer);
                }

            }
        } else {
            deviceMainService.save(deviceMain, deviceImgFile, deviceManualFile);
        }

        addMessage(redirectAttributes, "保存设备成功");
        return "redirect:" + Global.getAdminPath() + "/devmng/deviceMain/?repage";
    }

    @RequiresPermissions("devmng:deviceMain:edit")
    @RequestMapping(value = "delete")
    public String delete(DeviceMain deviceMain, RedirectAttributes redirectAttributes) {
        deviceMainService.delete(deviceMain);
        addMessage(redirectAttributes, "删除设备成功");
        return "redirect:" + Global.getAdminPath() + "/devmng/deviceMain/?repage";
    }
    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "treeData")
    public List<Map<String, Object>> treeData(@RequestParam(required = false) String extId, HttpServletResponse response) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<DeviceMain> list = deviceMainService.findList(new DeviceMain());
        for (int i = 0; i < list.size(); i++) {
            DeviceMain e = list.get(i);
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", e.getId());
            map.put("pId", "noparent");
            map.put("name", e.getDeviceName());
            mapList.add(map);
        }
        return mapList;
    }

    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "deptTreeData")
    public List<Map<String, Object>> deptTreeData(HttpServletResponse response) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<Office> officeList = officeService.findList(true);
        for (int i = 0; i < officeList.size(); i++) {
            Office e = officeList.get(i);
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", "dept_" + e.getId());
            map.put("pId", "dept_" + e.getParentId());
            map.put("name", e.getName());
            map.put("nocheck", true);
            mapList.add(map);
        }

        List<DeviceMain> list = deviceMainService.findList(new DeviceMain());
        for (int i = 0; i < list.size(); i++) {
            DeviceMain e = list.get(i);
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", e.getId());
            map.put("pId", "dept_" + e.getSysOffice().getId());
            if (e.getDeviceUser() != null) {
                map.put("name", e.getDeviceName() + "(" + e.getDeviceUser().getName() + ")");
            } else {
                map.put("name", e.getDeviceName() + "(无包机人)");
            }
            mapList.add(map);
        }
        return mapList;
    }

    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "deptTreeDataForEdit")
    public List<Map<String, Object>> deptTreeDataForEdit(@RequestParam(value = "taskMainId", required = false) String taskMainId,
                                                         HttpServletResponse response) {

        List<TaskDetail> taskDetailList = null;
        if (StringUtils.isNotEmpty(taskMainId)) {
            TaskDetail taskDetail = new TaskDetail();
            taskDetail.setTaskMainId(taskMainId);
            taskDetailList = taskDetailService.findList(taskDetail);
        } else {
            taskDetailList = Collections.emptyList();
        }
        Map<String, String> deviceMainIdMap = new HashMap<String, String>();
        for (TaskDetail taskDetail : taskDetailList) {
            deviceMainIdMap.put(taskDetail.getDeviceMainId(), "1");
        }

        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<Office> officeList = officeService.findList(true);
        for (int i = 0; i < officeList.size(); i++) {
            Office e = officeList.get(i);
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", "dept_" + e.getId());
            map.put("pId", "dept_" + e.getParentId());
            map.put("name", e.getName());
//            map.put("nocheck", true);
//            map.put("checked", true);
            mapList.add(map);
        }

        List<DeviceMain> list = deviceMainService.findList(new DeviceMain());
        for (int i = 0; i < list.size(); i++) {
            DeviceMain e = list.get(i);
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", e.getId());
            if (deviceMainIdMap.containsKey(e.getId())) {
                map.put("checked", true);
            }
            map.put("pId", "dept_" + e.getSysOffice().getId());
            if (e.getDeviceUser() != null) {
                map.put("name", e.getDeviceName() + "(" + e.getDeviceUser().getName() + ")");
            } else {
                map.put("name", e.getDeviceName() + "(无包机人)");
            }
            mapList.add(map);
        }
        return mapList;
    }

}